/**
 * axios二次封装
 */

import axios from 'axios'
import config from '../config/index.js'
import store from '@/store'
import router from '../router/index.js'
import { Message } from 'element-ui';


const TOKEN_INVALID = 'Token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'


// 创建axios实例对象，添加全局配置
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000
});



// 请求拦截
service.interceptors.request.use((req) => {
  if (req.method === 'get' || req.method === 'GET') {
    req.url = decodeURIComponent(req.url)
  }
  if (localStorage.getItem("token")) {
    req.headers.token = localStorage.getItem("token")
  }
  return req;
})

// 响应拦截
service.interceptors.response.use((res) => {
  const { code, data, msg, } = res.data;
  if (msg.indexOf("401") !== -1) {
    Message.error({
      message: "您的身份已过期,1秒后跳转至登陆页",
      duration: 1000,
    })
    setTimeout(() => {
      router.push('/login')
    }, 1500)

  }

  if (code === 200) {
    if (!res.data.success) {
      Message.error({
        message: msg,
        duration: 2 * 1000,
      })
      console.error(msg || NETWORK_ERROR)
      return Promise.reject(msg || NETWORK_ERROR)
    } else {
      return res.data
    }

  } else if (code == 401) {
    console.error(TOKEN_INVALID)
    Message.error({
      message: msg,
      duration: 1200,
    })
    setTimeout(() => {
      router.push('/login')
    }, 1000)
    return Promise.reject(TOKEN_INVALID)
  } else {
    Message.error({
      message: msg,
      duration: 1200,
    })
    console.error(msg || NETWORK_ERROR)
    return Promise.reject(msg || NETWORK_ERROR)
  }

},(error)=>{
  // const { status, data, msg, } = error.response;
  console.log(error)
  if(error.response.status === 404){
    Message.error({
      message: "404 no found",   
      duration: 1200,
    })
  }else{
    Message.error({
      message: error.response.data.msg,
      duration: 1200,
    })
  }
  
  return Promise.reject(msg || NETWORK_ERROR)
});


/**
 * 请求核心函数
 * @param {*} options 请求配置
 */

function request(options) {
  options.method = options.method || 'get'
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data || options.params;
  }

  let isMock = config.mock;
  if (typeof options.mock != 'undefined') {
    isMock = options.mock;
  }


  if (config.env === 'prod') {
    service.defaults.baseURL = config.baseApi
  } else {
    service.defaults.baseURL = isMock ? config.mockApi : config.baseApi
  }

  return service(options)
}


['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
  request[item] = (url, data, options) => {
    return request({
      url,
      data,
      method: item,
      ...options
    })
  }
})

export default request;